﻿CREATE PROCEDURE [dbo].[sp_BuildBatchForResubmission]
	@BatchID					uniqueidentifier OUTPUT,
	@Debug						bit			   = 0
AS

	IF @Debug = 1
	BEGIN
		print 'sp_BuildBatchForResubmission: @vCurrentTime = ' + CONVERT(varchar(50), GETDATE())
	END

	-- Mark the Batch and the Batch Messages for resubmission
	BEGIN TRY

		BEGIN TRANSACTION T1

			--If there is already a batch processing don't update.
			IF(NOT EXISTS(SELECT TOP 1 1 FROM BatchResubmission WHERE [Status] = N'Processing'))
			BEGIN

				DECLARE @vCurrentBatchId as UNIQUEIDENTIFIER
				SET @vCurrentBatchId = (
					SELECT TOP 1 b.[BatchID]
					FROM [BatchResubmission] b
					WHERE b.[Status] = N'Pending'
					ORDER BY b.[CreatedBy] ASC
				)

				UPDATE [BatchResubmission]
				SET
					[StartDatetime] = GETDATE()
					,[LastModifiedBy] = SUSER_SNAME()
					,[LastModified] = GETDATE()
					, [Status] = N'Processing'
				WHERE
					[BatchID] = @vCurrentBatchId

				UPDATE [BatchResubmissionMessage]
				SET	[ProcessingServer] = @@SERVERNAME
					, [Status] = N'Processing'
					, [LastModified] = GETDATE()
				WHERE
					[MessageBatchID] = @vCurrentBatchId
					AND [Status] = N'Pending'

			END

			SET @BatchID = (SELECT TOP 1 BatchID FROM BatchResubmission WHERE [Status] = N'Processing')

		COMMIT TRANSACTION T1
	END TRY
	BEGIN CATCH
		DECLARE @error int, @message varchar(4000), @xstate int;
        SELECT @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();

		ROLLBACK TRANSACTION T1
        
		RAISERROR ('[sp_BuildBatchForResubmission]: %d: %s', 16, 1, @error, @message) ;
        RETURN;
	END CATCH

RETURN 0
